﻿using MediatR;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.WorkFlow;

namespace SmartProduction.Read.API.Application.CommandHandlers.WorkFlow
{

    /// <summary>
    /// 工作流查询命令处理
    /// </summary>
    public class WorkFlowQueryCommandHandler:IRequestHandler<WorkFlowQueryCommand,APIResult<APIPaing<Workflows>>>
    {
        /// <summary>
        /// 工作流仓储
        /// </summary>
        private readonly IBaseRepository<Workflows> workRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="workRep">工作流仓储</param>
        public WorkFlowQueryCommandHandler(IBaseRepository<Workflows> workRep)
        {
            this.workRep = workRep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回的任务</returns>
        public async Task<APIResult<APIPaing<Workflows>>> Handle(WorkFlowQueryCommand request, CancellationToken cancellationToken)
        {
           APIResult<APIPaing<Workflows>> result=new APIResult<APIPaing<Workflows>>();

            var list = workRep.GetAll().Result.Where(x => x.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.WorkflowsName))
            {
                list = list.Where(x => x.WorkflowsName.Contains(request.WorkflowsName));
            }
            if (request.IsStatus!=null)
            {
                list = list.Where(x=>x.IsStatus==request.IsStatus);
            }
            int totalcount=list.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.size);

            var pagelist = list.OrderByDescending(x => x.WorkflowsId).Skip((request.index - 1) * request.size).Take(request.size);


            APIPaing<Workflows> aPIPaing = new APIPaing<Workflows>();

            aPIPaing.TotalCount = totalcount;
            aPIPaing.PageCount = totalpage;

            aPIPaing.Items=pagelist.ToList();
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = aPIPaing;

            return await Task.FromResult(result);
        }
    }
}
